﻿using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Configuration.Json;
using System.Reflection;
using System.Text.Encodings.Web;
using System.Text.Json;
using System.Text.Unicode;

namespace Utils
{
    /// <summary>
    /// 配置文件工具类
    /// </summary>
    public class ConfigUtil
    {
        private static ConfigurationBuilder _builder;

        #region 获取配置文件配置
        /// <summary>
        /// 获取配置文件配置
        /// </summary>
        public static IConfiguration GetConfiguration()
        {
            if (_builder == null)
            {
                string basePath = Path.GetDirectoryName(AppDomain.CurrentDomain.BaseDirectory).Replace(@"\", "/");
                _builder = new ConfigurationBuilder();
                _builder.AddJsonFile(Path.Combine(basePath, "appsettings.json"), optional: true, reloadOnChange: true);
            }

            return _builder.Build();
        }
        #endregion

        #region 保存配置
        /// <summary>
        /// 保存配置
        /// </summary>
        public static void Save(string key, object value)
        {
            string basePath = Path.GetDirectoryName(AppDomain.CurrentDomain.BaseDirectory).Replace(@"\", "/");
            string jsonPath = Path.Combine(basePath, "appsettings.json");
            var jsonDict = JsonSerializer.Deserialize<Dictionary<string, object>>(File.ReadAllText(jsonPath));
            if (jsonDict != null) jsonDict[key] = value;
            File.WriteAllText(jsonPath, JsonSerializer.Serialize(jsonDict, new JsonSerializerOptions() { WriteIndented = true }));
        }
        #endregion

        #region FTP配置
        public static string FtpPath => $"ftp://{FtpIp}:{FtpPort}";

        public static string? FtpIp => GetConfiguration().GetSection("Ftp").GetValue<string>("FtpIp");

        public static string FtpPort => GetConfiguration().GetSection("Ftp").GetValue<string>("FtpPort");

        public static string FtpUser => GetConfiguration().GetSection("Ftp").GetValue<string>("FtpUser");

        public static string FtpPassword => GetConfiguration().GetSection("Ftp").GetValue<string>("FtpPassword");
        #endregion

    }
}
